package com.manong.bookstore.user.session;

import org.apache.catalina.User;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class UserSessionManager {
	private final HashMap<String, UserSession> sessions;

	public UserSessionManager() {
		sessions = new HashMap<>();

		System.out.println("-> UserSessionManager: created.");
	}

//	public UserSessionManager(int userSessionScanInterval, long userSessionTimeout) {
//		sessions = new HashMap<>();
//
//		new Thread(new CheckExpire(userSessionScanInterval, userSessionTimeout, this)).start();
//	}

	public synchronized boolean exist(String sessionId) {
		UserSession userSession = sessions.get(sessionId);

		if(userSession != null) {
			userSession.updateLastAccessTime();
			return true;
		}
		else
			return false;
	}

	public synchronized UserSession getUserSession(String sessionId) {
		UserSession userSession = sessions.get(sessionId);

		if(userSession != null) {
			userSession.updateLastAccessTime();
			return userSession;
		}
		else
			return null;
	}

	public synchronized String addUserSession() {
		String sessionId = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
		UserSession userSession = new UserSession(sessionId);

		sessions.put(sessionId, userSession);

		return sessionId;
	}

	public synchronized boolean delUserSession(String sessionId) {
		return sessions.remove(sessionId) != null;
	}

	public synchronized Map<String, UserSession> getUserSessions() { return sessions; }
}
